//
//  XJHomeViewController.swift
//  XJWeiBO
//
//  Created by 452608533 on 16/7/19.
//  Copyright © 2016年 452608533. All rights reserved.
//

import UIKit

class XJHomeViewController: XJVisitorViewController {
    
    lazy var statusListViewModel: XJStatusListViewModel = XJStatusListViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //判断是否登录
        if !isLogin {
            visitorView?.setupVisitorViewInfo(nil, title: nil)
            return
        }
        setupTableViewInfo()
        getHomeData()
    }
    //设置tableview
    func setupTableViewInfo() {
        
        tableView.dataSource = self
        
        tableView.delegate = self
        
        tableView.registerClass(XJStatusCell.self, forCellReuseIdentifier: "cell")
        
        tableView.estimatedRowHeight = 210
        
        tableView.tableFooterView = indicatorView
        tableView.addSubview(refreshControl)
        
        refreshControl.addTarget(self, action: "refreshAction", forControlEvents: UIControlEvents.ValueChanged)
    }
    func refreshAction(){
        getHomeData()
        
    }
    //懒加载
    
    private lazy var indicatorView: UIActivityIndicatorView = {
        
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        view.color = UIColor.orangeColor()
        return view
    }()
    
    private lazy var refreshControl: XJRefreshControl = XJRefreshControl()
}

extension XJHomeViewController:UITableViewDataSource, UITableViewDelegate{
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusListViewModel.statusList.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! XJStatusCell
        cell.statusViewModel = statusListViewModel.statusList[indexPath.row]
        return cell
    }
    
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        
        if indexPath.row == statusListViewModel.statusList.count - 1 && !indicatorView.isAnimating(){
            indicatorView.startAnimating()
            getHomeData()
        }
    }
    
    
}

extension XJHomeViewController{
    
    func getHomeData() {
        
        statusListViewModel.loadHomeData(indicatorView.isAnimating()) { (isSuc) -> () in
            self.endRefreshing()
            
            if !isSuc {
                return
            }
            self.tableView.reloadData()
        }
        
    }
    
    func endRefreshing() {
        self.indicatorView.stopAnimating()
        self.refreshControl.endRefreshing()
    }
}
